package com.ax.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ax.common.core.constants.HttpConstants;
import com.ax.common.core.domain.R;
import com.ax.common.core.enums.ResultCode;
import com.ax.common.core.enums.UserIdentity;
import com.ax.common.security.TokenService;
import com.ax.common.core.utils.JwtUtils;
import com.ax.common.security.domain.LoginUser;
import com.ax.common.security.exception.ServiceException;
import com.ax.system.domain.sysuser.SysUser;
import com.ax.system.domain.sysuser.dto.SysUserSaveDTO;
import com.ax.system.domain.sysuser.vo.LoginUserVo;
import com.ax.system.mapper.sysuser.SysUserMapper;
import com.ax.system.service.sysuser.ISysUserService;
import com.ax.system.utils.BCryptUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

//    配置jwt
    @Value("${jwt.secret}")
    private String secret;

    @Override
    public R<String> login(String userAccount, String password) {

        System.out.println(password);
        System.out.println(userAccount);
//        1.通过账号去数据查询对应的用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
//        sql写法 select password from tb_sys_user where user_account = #{userAccount}

        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId, SysUser::getPassword, SysUser::getNickName)
                .eq(SysUser::getUserAccount, userAccount));

        System.out.println(sysUser);
//        这里为何查不到用户名 account
        System.out.println(sysUserMapper.selectById(1));
        System.out.println(sysUserMapper.selectById(2));

//        System.out.println(sysUser.toString());
//        System.out.println(sysUser.getPassword());
//        System.out.println(sysUser.getUserAccount());


//      R loginResult = new R();
//      2.校验查询到的对象 为空
        if (sysUser == null) {
//            loginResult.setCode(ResultCode.AILED_USER_EXISTS.getCode());
//            loginResult.setMsg(ResultCode.AILED_USER_EXISTS.getMsg());
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
//        密码正确登录成功
        if (BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            System.out.println(1111);
//            loginResult.setCode(ResultCode.SUCCESS.getCode());
//            loginResult.setMsg(ResultCode.SUCCESS.getMsg());

//            生成jwt token密令
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", sysUser.getUserId());
           String token =  JwtUtils.createToken(claims, secret);
//           第三方机制中存储敏感信息
//            身份认真具体还要存储哪些信息 redis 表明用户身份字段 1 表示普通用户 2 表示管理员用户  对象

            return R.ok(tokenService.createToken(sysUser.getUserId(),secret, UserIdentity.ADMIN.getValue(),sysUser.getNickName()));
        }
//        否则错误失败
//        loginResult.setCode(ResultCode.FAILED_LOGIN.getCode());
//        loginResult.setMsg(ResultCode.FAILED_LOGIN.getMsg());
        return R.fail(ResultCode.FAILED_LOGIN);
    }


    @Override
    public R<LoginUserVo> info(String token) {

        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }

        System.out.println(token);

        LoginUser loginUser = tokenService.getLoginUser(token,secret);
        if (loginUser == null) {
            return R.fail();
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setNickName(loginUser.getNickName());
        return R.ok(loginUserVo);
    }

    @Override
    public boolean logout(String token) {
//        删除token
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }

        return tokenService.deleteLoginUser(token,secret);
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
//        将dto转为实体  为什么
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
//        处理新增的是否已存在
        if (CollectionUtil.isNotEmpty(sysUserList)) {
            //用户已经存在
            //自定义的异常   公共的异常类
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }

        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(sysUserSaveDTO.getPassword());

//
//        sysUser.setCreateTime(LocalDateTime.now());
//        sysUser.setCreateBy(1L);


        System.out.println();
        return sysUserMapper.insert(sysUser) ;

    }


}
